package com.egao.orderB.service.impl;

import cn.hutool.core.util.StrUtil;
import com.egao.common.core.constants.UserConstant;
import com.egao.common.core.utils.Utils;
import com.egao.common.core.utils.messages.PhoneUtils;
import com.egao.common.core.web.PageResult2;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
//import com.egao.orderB.mapper.BillMapper;
import com.egao.orderB.biz.BillFeeBiz;
import com.egao.orderB.biz.BillProcessBiz;
import com.egao.orderB.biz.MaintainFeeAttachBiz;
import com.egao.orderB.entity.Bill;
import com.egao.orderB.entity.BillFee;
import com.egao.orderB.entity.BillProcess;
import com.egao.orderB.entity.MaintainFeeAttach;
import com.egao.orderB.service.BillService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import com.egao.orderB.biz.BillBiz;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
//import javax.transaction.Transactional;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单管理服务实现类
 * @author : Doman
 * @date : 2020-05-28 14:12:19
 * @version ：1.0
 */
@Service
public class BillServiceImpl /*extends ServiceImpl<BillMapper, Bill> */implements BillService {

	@Autowired
	private BillBiz billBiz;
	@Autowired
	private BillProcessBiz billProcessBiz;
	@Autowired
	private BillFeeBiz billFeeBiz;
	@Autowired
	private MaintainFeeAttachBiz maintainFeeAttachBiz;

    /**
    @Override
    public PageResult<Bill> listPage(PageParam<Bill> page) {
        List<Bill> records = baseMapper.listPage(page);
        return new PageResult<>(records, page.getTotal());
    }

    @Override
    public List<Bill> listAll(Map<String, Object> page) {
        return baseMapper.listAll(page);
    } */

    @Override
    public JSONObject list(PageResult2<T> page, Bill bill, User loginUser) throws Exception {
        JSONObject ob = billBiz.list(page,bill,loginUser);
        JSONArray ja = ob.getJSONArray("data");
        if(ja != null && ja.size() > 0) {
            for(int i = 0; i < ja.size(); i ++) {
                JSONObject b = ja.getJSONObject(i);
                BillFee bf = new BillFee();
                bf.setBillId(b.getString("id"));
                b.put("billFeeList", billFeeBiz.list(bf, loginUser));

                BillProcess billProcess = new BillProcess();
                billProcess.setBillId(b.getString("id"));
                b.put("billProcessList", billProcessBiz.list(billProcess, loginUser));
            }
        }
        return ob;
    }

    @Override
    public List<Bill> list(Bill bill, User loginUser) {
        return billBiz.list(bill,loginUser);
    }

    @Override
    public Bill getById(Bill bill) {
        return billBiz.getById(bill);
    }

    //客户下单
    @Override
    @Transactional
    public JsonResult order(Bill bill, User loginUser) {
        if(Utils.isEmpty(bill.getDock())|| Utils.isEmpty(bill.getProvince())||
                Utils.isEmpty(bill.getWeight())|| Utils.isEmpty(bill.getBoxType())||
                Utils.isEmpty(bill.getPrice())||
                Utils.isEmpty(bill.getPackDate())||
                Utils.isEmpty(bill.getVessel())|| Utils.isEmpty(bill.getVoyage())||
                Utils.isEmpty(bill.getBillOfLading())||
                Utils.isEmpty(bill.getFactoryAddress())
                ){
            return JsonResult.error("请填写下单内容,操作失败!");
        }
        bill.setState("已下单");
        int key= billBiz.order(bill, loginUser);
        BillProcess bp = new BillProcess();
        bp.setCompanyId(UserConstant.COMPANY_ID+"");
        bp.setBillId(key+"");
        bp.setState("已下单");
        billProcessBiz.save(bp, loginUser);
        return JsonResult.ok("下单成功");
//        return JsonResult.error("下单失败");
    }

    //做单
    @Override
    @Transactional
    public JsonResult make(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已下单")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(Utils.isEmpty(bill.getDriver()) || Utils.isEmpty(bill.getDriverFreight())){
            return JsonResult.error("请填写司机信息,操作失败!");
        }
        bill.setState("已做单");
        if (billBiz.make(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已做单");
            billProcessBiz.save(bp, loginUser);
            PhoneUtils.sendMsg(bill.getDriverPhone(), "602245", new String[]{bill2.getBillOfLading()});
            return JsonResult.ok("做单成功");
        }
        return JsonResult.error("做单失败");
    }

    //司机接单
    @Override
    @Transactional
    public JsonResult driverReceive(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已做单")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }

        bill.setState("已接单");
        if (billBiz.driverReceive(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已接单");
            billProcessBiz.save(bp, loginUser);
//            PhoneUtils.sendMsg(bill2.getContactsPhone(),
//                    "597088",
//                    new String[]{"姓名:"+bill2.getDriver()+",手机:"+bill2.getDriverPhone()});
            return JsonResult.ok("接单成功");
        }
        return JsonResult.error("接单失败");
    }

    //提箱
    @Override
    @Transactional
    public JsonResult upBox(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已接单")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(Utils.isEmpty(bill.getBoxNum())||Utils.isEmpty(bill.getBoxNumPic())||
            Utils.isEmpty(bill.getSealno())||Utils.isEmpty(bill.getSealnoPic())
            ){
            return JsonResult.error("请填写提箱信息,操作失败!");
        }
        bill.setState("已提箱");
        if (billBiz.upBox(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已提箱");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("提箱成功");
        }
        return JsonResult.error("提箱失败");
    }

    //到厂
    @Override
    @Transactional
    public JsonResult arrivedFactory(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已提箱")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(Utils.isEmpty(bill.getArrivedFactoryLatitude())||Utils.isEmpty(bill.getArrivedFactoryLongitude())||
                Utils.isEmpty(bill.getArrivedFactoryDate())
            ){
            return JsonResult.error("请填写到厂信息,操作失败!");
        }
        bill.setState("已到厂");
        if (billBiz.arrivedFactory(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已到厂");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("到厂成功");
        }
        return JsonResult.error("到厂失败");
    }

    //离厂
    @Override
    @Transactional
    public JsonResult leaveFactory(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已到厂")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(Utils.isEmpty(bill.getLeavedFactoryDate())||Utils.isEmpty(bill.getLeavedFactoryLatitude())||
                Utils.isEmpty(bill.getLeavedFactoryLongitude())
        ){
            return JsonResult.error("请填写离厂信息,操作失败!");
        }
        bill.setState("已离厂");
        if (billBiz.leaveFactory(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已离厂");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("离厂成功");
        }
        return JsonResult.error("离厂失败");
    }

    //进港
    @Override
    @Transactional
    public JsonResult inPort(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已离厂")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(Utils.isEmpty(bill.getArrivedHarbourDate())||Utils.isEmpty(bill.getArrivedHarbourLatitude())||
            Utils.isEmpty(bill.getArrivedHarbourLongitude())||Utils.isEmpty(bill.getPreEntryPic())
            ){
            return JsonResult.error("请填写进港信息,操作失败!");
        }
        bill.setState("已进港");
        if (billBiz.inPort(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已进港");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("进港成功");
        }
        return JsonResult.error("进港失败");
    }

    //发起费用清单
    @Override
    @Transactional
    public JsonResult costBill(Bill bill, User loginUser) throws Exception {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("已进港")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        bill.setState("发起费用清单");
        if (billBiz.costBill(bill, loginUser)) {
            for (BillFee billFee: bill.getBillFeeList()) {
                if(Utils.isEmpty(billFee.getBillId())){
                    throw new Exception("请填写订单id,操作失败!");
                }
                billFeeBiz.save(billFee, loginUser);

                //司机发起费用申请的同时,平台插入相对应的应收附加费
                MaintainFeeAttach maintainFeeAttach = new MaintainFeeAttach();
                maintainFeeAttach.setBoxType(billFee.getBoxType());
                maintainFeeAttach.setName(billFee.getFeeName());
                maintainFeeAttach.setType("平台");
                List<MaintainFeeAttach> maintainFeeAttachList = maintainFeeAttachBiz.list(maintainFeeAttach,loginUser);
                if(maintainFeeAttachList!=null && maintainFeeAttachList.size()==1) {
                    maintainFeeAttach = maintainFeeAttachList.get(0);
                    if(maintainFeeAttach.getPrice()!=null){
                        BillFee billFee2 = (BillFee)billFee.clone();
                        billFee2.setPrice(maintainFeeAttach.getPrice());
                        billFee2.setType("应收");
                        billFeeBiz.save(billFee2, loginUser);
                    }
                }
            }

            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("发起费用清单");
            billProcessBiz.save(bp, loginUser);

            //添加司机的运费
            BillFee billFee = new BillFee();
            billFee.setBillId(bill2.getId());
            billFee.setCompanyId(UserConstant.COMPANY_ID+"");
            billFee.setType("应付");
            billFee.setFeeName("运费");
            billFee.setPrice(bill2.getDriverFreight());
            billFeeBiz.save(billFee, loginUser);



            return JsonResult.ok("发起费用清单成功");
        }
        return JsonResult.error("发起费用清单失败");
    }

    //司机费用审核时间
    @Override
    @Transactional
    public JsonResult driverFeeVerify(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!(bill2.getState().equals("发起费用清单") || bill2.getState().equals("货代费用已审核"))) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(bill2.getState().equals("发起费用清单")) {
            bill.setState("司机费用已审核");
        } else {
            bill.setState("所有费用已审核");
        }
        if (billBiz.driverFeeVerify(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("司机费用已审核");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("司机费用审核成功");
        }
        return JsonResult.error("司机费用审核失败");

    }

    //货代费用审核时间
    @Override
    @Transactional
    public JsonResult verify(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!(bill2.getState().equals("发起费用清单") || bill2.getState().equals("司机费用已审核"))) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        if(bill2.getState().equals("发起费用清单")) {
            bill.setState("货代费用已审核");
        } else {
            bill.setState("所有费用已审核");
        }
        if (billBiz.verify(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("货代费用已审核");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("货代费用审核成功");
        }
        return JsonResult.error("货代费用审核失败");
    }

    //客户确认
    @Override
    @Transactional
    public JsonResult customerVerify(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(!bill2.getState().equals("所有费用已审核")) {
            return JsonResult.error("当前状态为"+ bill2.getState() + ",操作失败!");
        }
        bill.setState("结单");
        if (billBiz.customerVerify(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("结单");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("客户确认成功");
        }
        return JsonResult.error("客户确认失败");
    }

    //订单取消
    @Override
    @Transactional
    public JsonResult billCancel(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            if(!(bill2.getState().equals("已下单") || bill2.getState().equals("已做单"))) {
                return JsonResult.error("当前状态为"+ bill2.getState() + ",不能取消订单!");
            }
        }
        if (billBiz.remove(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("取消订单");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("取消订单成功");
        }
        return JsonResult.error("取消订单失败");
    }

    //应收
    @Override
    @Transactional
    public JsonResult receivable(Bill bill, User loginUser) {
        if(bill.getId()==null) {
            return JsonResult.error("操作失败,请联系平台管理员!");
        }
        Bill bill2 = billBiz.getById(bill);
        if(bill2.getFeeState()!=null && bill2.getFeeState().contains("已付款")) {
            bill.setFeeState("已收款,已付款");
        } else {
            bill.setFeeState("已收款");
        }
        if (billBiz.feeState(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已收款");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("应收确认成功");
        }
        return JsonResult.error("应收确认失败");
    }

    //应付
    @Override
    @Transactional
    public JsonResult payable(Bill bill, User loginUser) {
        if(bill.getId()==null) {
            return JsonResult.error("操作失败,请联系平台管理员!");
        }
        Bill bill2 = billBiz.getById(bill);
        if(bill2.getFeeState()!=null && bill2.getFeeState().contains("已收款")) {
            bill.setFeeState("已收款,已付款");
        } else {
            bill.setFeeState("已付款");
        }

        if (billBiz.feeState(bill, loginUser)) {
            BillProcess bp = new BillProcess();
            bp.setCompanyId(UserConstant.COMPANY_ID+"");
            bp.setBillId(bill.getId());
            bp.setState("已付款");
            billProcessBiz.save(bp, loginUser);
            return JsonResult.ok("应付确认成功");
        }
        return JsonResult.error("应付确认失败");
    }

    @Transactional
    @Override
    public JsonResult save(Bill bill, User loginUser) {
        if (billBiz.save(bill, loginUser)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    @Transactional
    @Override
    public JsonResult update(Bill bill, User loginUser) {
        Bill bill2 = billBiz.getById(bill);
        if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            if(!(bill2.getState().equals("已下单") || bill2.getState().equals("已下单"))) {
                return JsonResult.error("当前状态为"+ bill2.getState() + ",不能修改订单!");
            }
        }
        if (StrUtil.hasBlank( bill.getId(),
                bill.getDock(), bill.getProvince(),
                bill.getWeight(), bill.getBoxType(),
                bill.getPrice(), bill.getPackDate(),
                bill.getVessel(), bill.getVoyage(),
                bill.getBillOfLading(), bill.getFactoryAddress())
        ) {
            return JsonResult.error("请完整填写修改内容,操作失败!");
        }
        if (billBiz.update(bill, loginUser)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Transactional
    @Override
    public JsonResult remove(Bill bill, User loginUser) {
        if (billBiz.remove(bill, loginUser)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
